package com.example.demo.controller;

import com.example.demo.utils.DateSolve;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.BitOP;
import redis.clients.jedis.Jedis;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("test")
public class TestController {

    @Autowired
    private RedisTemplate redisTemplate;

    Jedis jedis = null;

    //登录
    @PostMapping("login")
    public String login(@RequestParam(value = "date") String date,
                        @RequestParam(value = "userId") Integer userId,
                        @RequestParam(value = "b") boolean b
    ) {
        redisTemplate.opsForValue().setBit(date, userId.longValue(), b);

        redisTemplate.opsForValue().setBit(String.valueOf(userId), Long.parseLong(date) * 8, b);

        return "在" + date + "用户" + userId + "是否登录? " + b;
    }

    //统计几天内的活跃的用户数
    @GetMapping("getActiveCount")
    public long getActiveCount(@RequestParam("days") Integer days) {

        jedis = new Jedis("1.117.82.39", 6379);
        jedis.auth("hong921.");
        //获取前几天内的日期字符串数组
        String str[] = DateSolve.pastDay(days);
        jedis.bitop(BitOP.OR, "Count", str);
        return jedis.bitcount("Count");
    }

    //统计用户在几天内的登录次数
    @GetMapping("getLoginTimes")
    public long getLoginTimes(@RequestParam(value = "userId") String userId,
                              @RequestParam("days") Integer days) throws ParseException {

        jedis = new Jedis("1.117.82.39", 6379);
        jedis.auth("hong921.");

        //获取当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String time = sdf.format(new Date());

        //获取前第几天的时间
        Date now = sdf.parse(time);
        String past = DateSolve.getPastDate(days - 1, now);

        return jedis.bitcount(userId, Long.parseLong(past), Long.parseLong(time));
    }

}
